package com.trg.flex.dp
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.collections.CursorBookmark;
	import mx.collections.ICollectionView;
	import mx.collections.IList;
	import mx.collections.IViewCursor;
	import mx.events.CollectionEvent;
	import mx.utils.ObjectUtil;
	
	public class LocalDataProvider extends DataProvider
	{
		public function LocalDataProvider(source:* = null)
		{
			super();
			this.source = source;
		}
		
		protected var collection:ICollectionView;
		protected var _source:*;
		
		[Bindable]
		public function set source(source:*):void {
			if (collection != null) {
				collection.removeEventListener(CollectionEvent.COLLECTION_CHANGE, collectionChangedHandler);
			}
			
			_source = source;
			if (source is Array) {
				collection = new ArrayCollection(source as Array);
			} else if (source is ICollectionView) {
				collection = source as ICollectionView;
				collection.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionChangedHandler);
			} else {
				collection = null;
			}
		}
		
		public function get source():* {
			return _source;
		}
		
		protected function collectionChangedHandler(event:CollectionEvent):void {
			refreshInternal(false);
			dispatchEvent(new Event(TOTAL_RESULTS_CHANGED));
		}
		
		override protected function refreshData():Boolean {
			refreshInternal(true);
			return true;
		}
		
		protected function refreshInternal(refreshCollection:Boolean):void {
			if (collection == null) {
				data.source = null;
				return;
			}
			
			if (refreshCollection) {
				collection.sort = _sort;
				collection.filterFunction = _filterFunction;
				collection.refresh();
				dispatchEvent(new Event(TOTAL_RESULTS_CHANGED));
			}
			
			if (_resultsPerPage < 1 && collection is IList) {
				//whole list	
				data.source = IList(collection).toArray();
			} else {
				var cursor:IViewCursor = collection.createCursor();
				var temp:Array = [];
				cursor.seek(CursorBookmark.FIRST, _page * _resultsPerPage);
				for (var i:int = 0; i < _resultsPerPage; i++) {
					if (cursor.afterLast) {
						break;
					} else {
						temp[i] = cursor.current;
						cursor.moveNext();
					}
				}
				data.source = temp;
			}
			
			dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE));
		}
		
		override public function get totalResults():int {
			return (collection != null) ? collection.length : 0;
		}
		
	}
}